package com.ym.medical.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ym.core.utils.tkmybatis.BaseSVImpl;
import com.ym.core.utils.tkmybatis.TK;
import com.ym.medical.dao.AddressListDao;
import com.ym.medical.domain.entity.AddressGroupEntity;
import com.ym.medical.domain.entity.AddressListEntity;
import com.ym.medical.domain.param.AddressGroupParam;
import com.ym.medical.domain.vo.AddressListVo;
import com.ym.medical.domain.vo.DoctorLinkVo;
import com.ym.medical.enums.AddressGroupAlgIdentEnum;
import com.ym.medical.enums.AddressGroupAlgTypeEnum;
import com.ym.medical.enums.AddressListIdTypeEnum;
import com.ym.medical.enums.SystemGroupEnum;
import com.ym.medical.service.IAddressGroupSV;
import com.ym.medical.service.IAddressListSV;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ComputerName:LAPTOP-6GI4HOI6
 * Author:625
 * Date: 2019-05-22
 * Time: 14:14:51
 * 服务实现类
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AddressListSVImpl extends BaseSVImpl<AddressListEntity, AddressListDao> implements IAddressListSV {

	@Autowired
	private IAddressGroupSV addressGroupSV;

	@Override
	public Long addFriend(Long patientId, Long currUserId, String idType, Long groupId) {
		String idTypeEnum = null;
		String algName = null;
		String algIdent = null;
		if ("01".equals(idType)) {
			// 用户ID/即粉丝/小程序
			idTypeEnum = AddressListIdTypeEnum.THE_USER.getKey();
			algName = SystemGroupEnum.PATIENT.FANS.getName();
			algIdent = AddressGroupAlgIdentEnum.IN_PATIENTS_WITH.getKey();
		} else if ("02".equals(idType)) {
			// 医生
			idTypeEnum = AddressListIdTypeEnum.THE_USER.getKey();
			algName = SystemGroupEnum.DOCTOR.ALL.getName();
			algIdent = AddressGroupAlgIdentEnum.THE_DOCTOR.getKey();
		} else if ("03".equals(idType)) {
			// 患者
			idTypeEnum = AddressListIdTypeEnum.IN_PATIENTS_WITH.getKey();
			algName = SystemGroupEnum.PATIENT.INQUIRY.getName();
			algIdent = AddressGroupAlgIdentEnum.IN_PATIENTS_WITH.getKey();
		}

		// 1.判断是否有分组
		if (groupId == null) {
			AddressGroupParam addressGroupModel = new AddressGroupParam();
			addressGroupModel.setAlgName(algName);
			addressGroupModel.setAlgIdent(algIdent);
			addressGroupModel.setUserId(currUserId);
			addressGroupModel.setAlgType(AddressGroupAlgTypeEnum.System.getKey());
			AddressGroupEntity addressGroup = addressGroupSV.selectOne(addressGroupModel.covert());
			if (addressGroup == null) {
				addressGroupSV.insert(addressGroupModel.covert());
				groupId = addressGroupModel.getId();
			} else {
				groupId = addressGroup.getId();
			}
		}
		// 保存的关系
		AddressListEntity addressList = new AddressListEntity();
		addressList.setAlgId(groupId);
		addressList.setIdType(idTypeEnum);
		addressList.setUserId(patientId);
		// 2.判断是否已经添加好友,如果是自定义分组，则移动，否则新增
		AddressGroupEntity addressGroup = addressGroupSV.selectById(groupId);
		if (addressGroup.getAlgType().equals(AddressGroupAlgTypeEnum.THE_USER.getKey())) {
			//自定义分组，先更新移动，没记录添加.先查出当前登录人的所有自定义分组，更新
			List<AddressGroupEntity> addressGroups = addressGroupSV.selectList(AddressGroupParam.builder()
					.userId(currUserId)
					.algType(AddressGroupAlgTypeEnum.THE_USER.getKey())
					.algIdent(algIdent)
					.build().covert());
			long updateCount = this.updateByParams(addressList,
					TK.selectWhere(AddressListEntity.class)
							.andEqualTo(AddressListEntity::getUserId, patientId)
							.andEqualTo(AddressListEntity::getIdType, idTypeEnum)
							.andIn(AddressListEntity::getAlgId, addressGroups.stream().map(AddressGroupEntity::getId).collect(Collectors.toList()))
							.end()
			);
			if (updateCount == 0) {
				// 3.建立好友关系
				this.insert(addressList);
			}
		} else {
			// 系统分组，不重复添加
			int count = this.countByParams(AddressListEntity.builder().userId(patientId).algId(groupId).idType(idTypeEnum).build());
			if (count == 0) {
				// 3.建立好友关系
				this.insert(addressList);
			}
		}
		return addressList.getId();
	}


	@Override
	public PageInfo<DoctorLinkVo> listDoctor(String keywords, Long userId, int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		List<DoctorLinkVo> doctorLinkVos = mapper.listDoctor(keywords, userId);
		return new PageInfo(doctorLinkVos);
	}

	@Override
	public int cancelAttention(Long id) {
		int flag = this.deleteById(id);
		return flag;
	}

	@Override
	public List<AddressListVo> selectBeRelevant(Long doctorId) {
		return mapper.selectBeRelevant(doctorId);
	}

	/**
	 * 屏蔽患者
	 *
	 * @param id
	 * @param id1
	 * @param idType
	 * @param groupId
	 * @return
	 */
	@Override
	public int shieldFriend(Long id, Long id1, String idType, Long groupId, String type) {
		int rows = 0;
		if ("01".equals(type)) {
			//查询是否有屏蔽的分组 (已屏蔽患者)
			AddressGroupEntity group = addressGroupSV.selectOne(
					TK.select(AddressGroupEntity.class).where()
							.andEqualTo(AddressGroupEntity::getUserId, id1)
							.andEqualTo(AddressGroupEntity::getAlgType, AddressGroupAlgTypeEnum.System.getKey())
							.andEqualTo(AddressGroupEntity::getAlgName, SystemGroupEnum.PATIENT.SHIELD_PATIENT.getName())
							.andEqualTo(AddressGroupEntity::getAlgIdent, AddressGroupAlgIdentEnum.IN_PATIENTS_WITH.getKey())
							.end()
			);
			if (null == group) {
				//创建分组
				AddressGroupEntity addressGroup = new AddressGroupEntity();
				addressGroup.setAlgName(SystemGroupEnum.PATIENT.SHIELD_PATIENT.getName());
				addressGroup.setUserId(id1);
				addressGroup.setAlgType(AddressGroupAlgTypeEnum.System.getKey());
				addressGroup.setAlgIdent(AddressGroupAlgIdentEnum.IN_PATIENTS_WITH.getKey());
				addressGroupSV.insert(addressGroup);
				Long newGroupId = addressGroup.getId();
				//患者放入分组
				rows = addAddressList(newGroupId, id, idType);
			} else {
				Long groupId2 = group.getId();
				rows = addAddressList(groupId2, id, idType);

			}
		} else {
			//移出屏蔽分组(到问诊患者)
			//1.1查询 问诊患者分组的id
			AddressGroupEntity group = addressGroupSV.selectOne(
					TK.select(AddressGroupEntity.class).where()
							.andEqualTo(AddressGroupEntity::getUserId, id1)
							.andEqualTo(AddressGroupEntity::getAlgType, AddressGroupAlgTypeEnum.System.getKey())
							.andEqualTo(AddressGroupEntity::getAlgName, SystemGroupEnum.PATIENT.INQUIRY.getName())
							.andEqualTo(AddressGroupEntity::getAlgIdent, AddressGroupAlgIdentEnum.IN_PATIENTS_WITH.getKey())
							.end()
			);
			//1.2删除屏蔽患者分组关系
			this.deleteByParams(
					AddressListEntity
							.builder()
							.userId(id).idType(idType).algId(groupId)
							.build());

			//患者放入(问诊患者分组)分组
			AddressListEntity list = new AddressListEntity();
			list.setUserId(id);
			list.setIdType(idType);
			list.setAlgId(group.getId());
			list.setCreateTime(new Date());
			this.insert(list);
		}
		return 1;
	}

	/**
	 * 放入通讯录关系
	 *
	 * @param groupId
	 * @param userId
	 * @param idType
	 * @return
	 */
	private int addAddressList(Long groupId, Long userId, String idType) {
		//删除旧的关系
		this.deleteByParams(
				AddressListEntity
						.builder()
						.userId(userId).idType(idType)
						.build());
		//患者放入分组
		AddressListEntity list = new AddressListEntity();
		list.setUserId(userId);
		list.setIdType(idType);
		list.setAlgId(groupId);
		list.setCreateTime(new Date());
		this.insert(list);
		return 1;
	}
}
